from typing import Any

from sqlalchemy.ext.asyncio import AsyncSession

from crewplus.apps.account.schemas.account import AccountRegisterIn
from sqlalchemy.orm.strategy_options import _AbstractLoad
from config import settings
from apps.vadmin.auth.crud import RoleDal
from apps.vadmin.auth.models import VadminUser, VadminRole, vadmin_auth_user_roles
from apps.vadmin.auth.schemas import UserSimpleOut
from core.crud import DalBase
from core.exception import CustomException
from utils import status


class AccountDal(DalBase):

    def __init__(self, db: AsyncSession):
        super(AccountDal, self).__init__(db, VadminUser, UserSimpleOut)


    async def register_create_data(
            self,
            data: AccountRegisterIn,
            v_options: list[_AbstractLoad] = None,
            v_return_obj: bool = False,
            v_schema: Any = None
    ) -> Any:
        """
        Create admin user
        """
        # BEGIN-COMMENT, change to email registration
        # phone_existed: VadminUser = await self.get_data(telephone=data.telephone, v_return_none=True)
        # if phone_existed:
        #     raise CustomException("mobile is registered", code=status.HTTP_ERROR)
        # END-COMMENT
        if data.email is None:
            raise CustomException("email is required", code=status.HTTP_ERROR)
            
        email_existed: VadminUser = await self.get_data(email=data.email, v_return_none=True)
        if email_existed:
            raise CustomException("email is registered", code=status.HTTP_ERROR)
        
        password = data.password
        data.password = self.model.get_password_hash(password)
        data.avatar = data.avatar if data.avatar else settings.DEFAULT_AVATAR
        obj = self.model(**data.model_dump(exclude={'role_ids'}))
        await self.flush(obj)

        # [TODO] 注册默认先为管理员，否则没有菜单权限。后续改为普通用户 user
        role: VadminRole = await RoleDal(self.db).get_data(role_key="user")
        insert_user_role = vadmin_auth_user_roles.insert().values(user_id = obj.id, role_id = role.id)
        await self.db.execute(insert_user_role)

        return await self.out_dict(obj, v_options, v_return_obj, v_schema)





